package com.atguigu.study.service.impl;

import com.atguigu.study.annotations.MyRedisCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.study.entities.User;
import com.atguigu.study.service.UserService;
import com.atguigu.study.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * @author lenovo
 * @description 针对表【t_user(用户表)】的数据库操作Service实现
 * @createDate 2025-07-30 23:46:48
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    public static final String CACHE_KEY_USER = "user:";
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserMapper userMapper;

    @Override  //重写方法 将其保存到redis和mysql
    public boolean save(User user) {
        boolean retValue = false;

        log.info("插入之前user:{}", user);
        retValue = super.save(user);
        log.info("插入之后user:{}", user);
        log.info("=================================");

        if (retValue) {
            //先存到数据库里面，再在数据库中重新捞出新数据出来，做缓存
            user = this.userMapper.selectById(user.getId());
            //缓存key
            String key = CACHE_KEY_USER + user.getId();
            //往mysql里面插入成功随后再从mysql查询出来，再插入redis
            redisTemplate.opsForValue().set(key, user);
        }
        return retValue;
    }

//    @Override //查询  先查redis，若有直接返回  reids没有再去找mysql
//    public User getById(Serializable id) {
//        User user = null;
//        String key = CACHE_KEY_USER + id;
//        user = (User) redisTemplate.opsForValue().get(key);
//        if (user == null) { //redis无 查mysql
//            user = super.getById(id);
//        }
//        if(user!=null){ //mysql中有  把mysql中的数据写入到reids，方便下次查询redis可以命中
//            redisTemplate.opsForValue().set(key,user);
//        }
//        return user;
//    }
@Override
@MyRedisCache(keyPrefix = "user",matchValue = "#id")
public User getById(Serializable id)
{
    //从mysql查出来user 如何将缓存代码从业务代码中剥离，促使业务代码更简洁更易维护
    return this.userMapper.selectById(id);
}


}




